package com.hzw.net.manager

import android.util.Base64
import com.hzw.core.store.DataPreferences
import com.hzw.core.store.SpUtils
import com.hzw.net.utils.RSAUtils

/**
 * 用户信息管理
 */
object TokenManager {

    private const val KEY_CACHE_TOKEN = "KEY_CACHE_TOKEN"
    private const val KEY_CACHE_IS_LOGINING = "KEY_CACHE_IS_LOGINING"

    private var token: String = ""
    private var isLogining: Boolean? = null

    fun isLogining(): Boolean {
        if (isLogining == null) {
            isLogining = DataPreferences.getBoolean(KEY_CACHE_IS_LOGINING, false)
        }
        return isLogining == true
    }

    fun saveLogining(isLogining: Boolean) {
        TokenManager.isLogining = isLogining
        DataPreferences.putBoolean(KEY_CACHE_IS_LOGINING, isLogining)
    }

    fun getToken(): String {
        if (token.isEmpty()) {
            token = DataPreferences.getString(KEY_CACHE_TOKEN, "")
        }
        return token
    }

    fun saveToken(token: String) {
        TokenManager.token = token
        DataPreferences.putString(KEY_CACHE_TOKEN, token)
    }

    fun saveToken(token: String, isNeedDecrypt: Boolean = true) {
        if (isNeedDecrypt) {
            val tokenBytes = RSAUtils.decryptBase64RSA(
                token.toByteArray(),
                KeyStorageManager.getClientPrivateKey()!!.encoded,
                false
            )
            val realToken = String(tokenBytes!!)
            saveToken(realToken)
        } else {
            saveToken(token)
        }
    }

    fun isLogin(): Boolean = getToken().isNotEmpty()

    fun encryptToken(): String {
        val keyString = KeyStorageManager.getServerPublicKeyString()
        val token = getToken()
        if (token.isEmpty() || keyString.isNullOrEmpty()) {
            return ""
        }
        return String(
            RSAUtils.encryptRSA2Base64(
                token.toByteArray(),
                Base64.decode(
                    RSAUtils.formatPublicKey(String(Base64.decode(keyString, Base64.NO_WRAP))),
                    Base64.NO_WRAP
                ),
                true
            )
        )
    }
}